package edu.uoc.tdp.pac4.client.conexion;

import edu.uoc.tdp.pac4.beans.Matricula;
import edu.uoc.tdp.pac4.beans.Usuario;
import edu.uoc.tdp.pac4.remote.Conexion;
import edu.uoc.tdp.pac4.util.ComboItem;
import edu.uoc.tdp.pac4.util.LanguageUtils;
import java.rmi.RemoteException;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JComponent;
import javax.swing.JFormattedTextField;
import javax.swing.JOptionPane;
import javax.swing.JSpinner;
import javax.swing.table.DefaultTableModel;
import javax.swing.text.DateFormatter;

/**
 * Formulario de consulta de solicitudes de Matrícula
 * @author eSupport Netbeans
 */
public class PnlConsultaMatricula extends javax.swing.JDialog 
{
   private Conexion manager;
   private LanguageUtils language;
   private List<ComboItem> estados;
   private ArrayList<Matricula> matriculas;
   private Usuario usuario;

   /**
    * Creates new form PnlMatriculaGestor
    */
   public PnlConsultaMatricula(java.awt.Frame parent, boolean modal, Conexion manager, LanguageUtils language, Usuario usuario) 
   {
      super(parent, modal);
      this.manager = manager;
      this.language = language;
      this.usuario = usuario;
      initComponents();      
      setLocationRelativeTo(null);
      pnlFilter.setVisible(false);           
      fillFilterPanel();
      fillForm();
   }

   /**
    * This method is called from within the constructor to initialize the form.
    * WARNING: Do NOT modify this code. The content of this method is always
    * regenerated by the Form Editor.
    */
   @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrlPaneMatAsist = new javax.swing.JScrollPane();
        grdTable = new javax.swing.JTable();
        jTblMatriculaAsist = new javax.swing.JToolBar();
        jSeparator1 = new javax.swing.JToolBar.Separator();
        cmdFilter = new javax.swing.JToggleButton();
        cmdClose = new javax.swing.JButton();
        pnlFilter = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        txtName = new javax.swing.JTextField();
        lblFechaInicioCurso = new javax.swing.JLabel();
        cboEstado = new javax.swing.JComboBox();
        cmdSetFilter = new javax.swing.JButton();
        cmdFilterClean = new javax.swing.JButton();
        spnFechaFin = new javax.swing.JSpinner();
        spnFechaInicio = new javax.swing.JSpinner();
        lblFechaInicio = new javax.swing.JLabel();
        lblFechaFinCurso = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle(language.getProperty("cnxmatricula.consultarmatricula.title"));

        grdTable.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String [] {
                "Title 1", "Title 2", "Title 3", "Title 4"
            }
        ));
        jScrlPaneMatAsist.setViewportView(grdTable);

        jTblMatriculaAsist.setRollover(true);
        jTblMatriculaAsist.add(jSeparator1);

        cmdFilter.setIcon(new javax.swing.ImageIcon(getClass().getResource("/resources/funnel.png"))); // NOI18N
        cmdFilter.setText(language.getProperty("cnxmatricula.consultarmatricula.filtrar"));
        cmdFilter.setFocusable(false);
        cmdFilter.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        cmdFilter.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        cmdFilter.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cmdFilterActionPerformed(evt);
            }
        });
        jTblMatriculaAsist.add(cmdFilter);

        cmdClose.setIcon(new javax.swing.ImageIcon(getClass().getResource("/resources/arrow-curve-180.png"))); // NOI18N
        cmdClose.setText(language.getProperty("cnxmatricula.consultarmatricula.cerrar"));
        cmdClose.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cmdCloseActionPerformed(evt);
            }
        });

        pnlFilter.setBorder(javax.swing.BorderFactory.createEtchedBorder());

        jLabel1.setText(language.getProperty("cnxmatricula.consultarmatricula.alumno"));

        lblFechaInicioCurso.setText(language.getProperty("cnxmatricula.consultarmatricula.fechainiciocurso"));

        cmdSetFilter.setIcon(new javax.swing.ImageIcon(getClass().getResource("/resources/funnel--plus.png"))); // NOI18N
        cmdSetFilter.setText(language.getProperty("cnxmatricula.consultarmatricula.aplicar"));
        cmdSetFilter.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cmdSetFilterActionPerformed(evt);
            }
        });

        cmdFilterClean.setIcon(new javax.swing.ImageIcon(getClass().getResource("/resources/eraser.png"))); // NOI18N
        cmdFilterClean.setText(language.getProperty("cnxmatricula.consultarmatricula.limpiar"));
        cmdFilterClean.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cmdFilterCleanActionPerformed(evt);
            }
        });

        spnFechaFin.setModel(new javax.swing.SpinnerDateModel());
        spnFechaFin.setEditor(new javax.swing.JSpinner.DateEditor(spnFechaFin, "dd/MM/yyyy"));

        spnFechaInicio.setModel(new javax.swing.SpinnerDateModel());
        spnFechaInicio.setEditor(new javax.swing.JSpinner.DateEditor(spnFechaInicio, "dd/MM/yyyy"));

        lblFechaInicio.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
        lblFechaInicio.setText(language.getProperty("cnxmatricula.solicitudmatricula.fechainicio"));

        lblFechaFinCurso.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
        lblFechaFinCurso.setText(language.getProperty("cnxmatricula.consultarmatricula.fechafincurso"));

        javax.swing.GroupLayout pnlFilterLayout = new javax.swing.GroupLayout(pnlFilter);
        pnlFilter.setLayout(pnlFilterLayout);
        pnlFilterLayout.setHorizontalGroup(
            pnlFilterLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(pnlFilterLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(pnlFilterLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel1)
                    .addComponent(lblFechaInicio))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(pnlFilterLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(cboEstado, javax.swing.GroupLayout.PREFERRED_SIZE, 296, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(txtName, javax.swing.GroupLayout.PREFERRED_SIZE, 268, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 79, Short.MAX_VALUE)
                .addGroup(pnlFilterLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                    .addGroup(pnlFilterLayout.createSequentialGroup()
                        .addComponent(lblFechaFinCurso)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(spnFechaFin, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(pnlFilterLayout.createSequentialGroup()
                        .addComponent(lblFechaInicioCurso)
                        .addGap(29, 29, 29)
                        .addComponent(spnFechaInicio, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addGap(55, 55, 55)
                .addGroup(pnlFilterLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(cmdSetFilter, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(cmdFilterClean, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap())
        );
        pnlFilterLayout.setVerticalGroup(
            pnlFilterLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, pnlFilterLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(pnlFilterLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(txtName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel1)
                    .addComponent(cmdFilterClean)
                    .addComponent(lblFechaInicioCurso)
                    .addComponent(spnFechaInicio, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(7, 7, 7)
                .addGroup(pnlFilterLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(cmdSetFilter)
                    .addComponent(lblFechaFinCurso)
                    .addComponent(spnFechaFin, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(cboEstado, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(lblFechaInicio))
                .addContainerGap(13, Short.MAX_VALUE))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jTblMatriculaAsist, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(pnlFilter, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jScrlPaneMatAsist, javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(0, 0, Short.MAX_VALUE)
                        .addComponent(cmdClose)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jTblMatriculaAsist, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(pnlFilter, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrlPaneMatAsist, javax.swing.GroupLayout.DEFAULT_SIZE, 229, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(cmdClose)
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

   private void cmdCloseActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cmdCloseActionPerformed

      // Cierra el formulario
      this.dispose();
   }//GEN-LAST:event_cmdCloseActionPerformed

   private void cmdSetFilterActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cmdSetFilterActionPerformed
      
      int estado;
      
      if (cboEstado.getSelectedIndex() >= 0)
      {
         estado = estados.get(cboEstado.getSelectedIndex()).getId();
      }
      else
      {
         estado = -1;
      }
      
      fillForm(txtName.getText(), usuario.getNif(), estado, (Date) spnFechaInicio.getValue(), (Date) spnFechaFin.getValue());
      
   }//GEN-LAST:event_cmdSetFilterActionPerformed

   private void cmdFilterCleanActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cmdFilterCleanActionPerformed
      
      fillFilterPanel();
      fillForm();
      
   }//GEN-LAST:event_cmdFilterCleanActionPerformed

    private void cmdFilterActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cmdFilterActionPerformed

        pnlFilter.setVisible(cmdFilter.isSelected());

        // Si se oculta el filtro, se regenera la lista completa
        if (!pnlFilter.isVisible())
        {
            fillForm();
        }
        else
        {
            fillFilterPanel();
        }

    }//GEN-LAST:event_cmdFilterActionPerformed

   private void fillFilterPanel()
   {
      
      //Formateo del Spinner de fecha (formato de fecha y no editable con teclado)
      spnFechaInicio.setEditor(new JSpinner.DateEditor(spnFechaInicio, "dd/MM/yyyy"));
      JFormattedTextField ftf = getTextField(spnFechaInicio);
      ((DateFormatter) ftf.getFormatter()).setAllowsInvalid(false);	
      ftf.setEditable(false);        
      spnFechaFin.setEditor(new JSpinner.DateEditor(spnFechaFin, "dd/MM/yyyy"));
      ftf = getTextField(spnFechaFin);
      ((DateFormatter) ftf.getFormatter()).setAllowsInvalid(false);	
      ftf.setEditable(false);
        
      // Rellena el combo de filtros
      estados = new ArrayList<ComboItem>();
      estados.add(new ComboItem(language.getProperty("cnxmatricula.consultarmatricula.nofiltrar"), -1));
      estados.add(new ComboItem(Matricula.getStatusName(Matricula.MATRICULA_ESTADO_PENDIENTE, language), Matricula.MATRICULA_ESTADO_PENDIENTE));
      estados.add(new ComboItem(Matricula.getStatusName(Matricula.MATRICULA_ESTADO_ACEPTADA, language), Matricula.MATRICULA_ESTADO_ACEPTADA));
      estados.add(new ComboItem(Matricula.getStatusName(Matricula.MATRICULA_ESTADO_ANULADA, language), Matricula.MATRICULA_ESTADO_ANULADA));
      cboEstado.removeAll();
      cboEstado.setModel(new DefaultComboBoxModel(estados.toArray()));
      
      txtName.setText(usuario.getApellidos() + ", " + usuario.getNombre());
      txtName.setEnabled(false);
      
   }
   
   private void fillForm()
   {
      fillForm("", "", -1, new Date(), null);
   }
   
   private void fillForm(String name, String nif, int estado, Date fechaInicio, Date fechaFin)
   {
      SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");      
      
      // Rellena la tabla
      ArrayList<String> header = new ArrayList<String>();   // cabecera      
      header.add(language.getProperty("cnxmatricula.consultarmatricula.tableheaderNIF"));
      header.add(language.getProperty("cnxmatricula.consultarmatricula.tableheadernombre"));
      header.add(language.getProperty("cnxmatricula.consultarmatricula.tableheadercurso"));      
      header.add(language.getProperty("cnxmatricula.consultarmatricula.tableheadergrupo"));
      header.add(language.getProperty("cnxmatricula.consultarmatricula.tableheaderinicio"));
      header.add(language.getProperty("cnxmatricula.consultarmatricula.tableheaderfin"));
      header.add(language.getProperty("cnxmatricula.consultarmatricula.tableheaderestado"));
      
      String[][] gridData;
      ArrayList<String> row;

      try 
      {
         matriculas = manager.getMatriculas(usuario.getNombre(), usuario.getNif(), estado, fechaInicio, fechaFin);
         gridData = new String[matriculas.size()][8];
         int i = 0;
         for (Matricula matricula : matriculas)
         {            
            gridData[i][0] = matricula.getUsuarioNif();
            gridData[i][1] = matricula.getUsuarioNombre();
            gridData[i][2] = matricula.getCursoNombre();
            gridData[i][3] = matricula.getGrupoNombre();
            gridData[i][4] = (matricula.getFechaInicio() == null ? "?" : sdf.format(matricula.getFechaInicio()));
            gridData[i][5] = (matricula.getFechaFinal() == null ? "?" : sdf.format(matricula.getFechaFinal()));
            gridData[i][6] = Matricula.getStatusName(matricula.getEstado(), language);
            i++;
         }
         
         grdTable.setModel(new DefaultTableModel(gridData, header.toArray()));
         
         //Modificamos la tabla para que no sea editable
         grdTable.setModel(new DefaultTableModel(gridData, header.toArray()) {
               @Override
               public boolean isCellEditable(int row, int column) {
                    return false;
                }
            }); 
         
      } 
      catch (SQLException ex)
      {
         JOptionPane.showMessageDialog(null, 
                                       language.getProperty("err.sql") + "\n" + language.getProperty("err.detail") + ":\n\n" + ex.getMessage(), 
                                       language.getProperty("app.title"), 
                                       JOptionPane.ERROR_MESSAGE);
         
         // Registra el error en un archivo de LOG
         // Logger.getLogger(FrmResourcesRequest.class.getName()).log(Level.SEVERE, null, ex);
      }
      catch (RemoteException ex)
      {
         JOptionPane.showMessageDialog(null, 
                                       language.getProperty("err.rmi") + "\n" + language.getProperty("err.detail") + ":\n\n" + ex.getMessage(), 
                                       language.getProperty("app.title"), 
                                       JOptionPane.ERROR_MESSAGE);
         
      }
      catch (Exception ex) 
      {
         JOptionPane.showMessageDialog(null, 
                                       language.getProperty("err.generic") + "\n" + language.getProperty("err.detail") + ":\n\n" + ex.getMessage(), 
                                       language.getProperty("app.title"), 
                                       JOptionPane.ERROR_MESSAGE);
  
      }
   }
   
   /**
    * Método para formatear la fecha de un componente spinner
    * @param spinner
    * @return JFormattedTextField
    */
   private JFormattedTextField getTextField(JSpinner spinner) {
        
        JComponent editor = spinner.getEditor();
        if (editor instanceof JSpinner.DefaultEditor) {
            return ((JSpinner.DefaultEditor)editor).getTextField();
	    } 
        else 
        {
	        System.err.println(language.getProperty("err.jeditor")
	                           + spinner.getEditor().getClass()
	                           + " no es descendiente de DefaultEditor");
	        return null;
        }
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JComboBox cboEstado;
    private javax.swing.JButton cmdClose;
    private javax.swing.JToggleButton cmdFilter;
    private javax.swing.JButton cmdFilterClean;
    private javax.swing.JButton cmdSetFilter;
    private javax.swing.JTable grdTable;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JScrollPane jScrlPaneMatAsist;
    private javax.swing.JToolBar.Separator jSeparator1;
    private javax.swing.JToolBar jTblMatriculaAsist;
    private javax.swing.JLabel lblFechaFinCurso;
    private javax.swing.JLabel lblFechaInicio;
    private javax.swing.JLabel lblFechaInicioCurso;
    private javax.swing.JPanel pnlFilter;
    private javax.swing.JSpinner spnFechaFin;
    private javax.swing.JSpinner spnFechaInicio;
    private javax.swing.JTextField txtName;
    // End of variables declaration//GEN-END:variables
}
